import {FC, memo, useMemo, useRef} from "react";
import {VisualEditorBlockData} from "../atoms/container.atom";
import './block.scss'
import {useAdjustPosition} from "./useAdjustPosition";
import {useBlockDrag} from "./useBlockDrag";
import {VisualEditorComponentProps} from "../../plugins/menu.registry";

interface PageProps {
    block: VisualEditorBlockData;
    render: ((defineProps: any) => JSX.Element) | undefined;
    commandsMap: any
}

const Block: FC<PageProps> = memo((props) => {
    const {block, render, commandsMap} = props
    const blockRef = useRef<HTMLDivElement>(null)
    // 调整位置
    useAdjustPosition(block, blockRef)
    const {onMouseDown} = useBlockDrag(block, commandsMap)
    // 控制block不受其他数据影响而重新渲染
    const BlockMemo = useMemo(() => {
        const res: FC<{
            defineProps:  VisualEditorComponentProps | undefined
        }> = ({defineProps}) => {
            return <div
                ref={blockRef}
                className={`block ${block.focus ? 'block-focus' : ''}`}
                style={{left: block.left + 'px', top: block.top + 'px', transform: block.transform}}
                onMouseDown={(e) => onMouseDown(e)}
            >{render && render(defineProps)}</div>
        }
        return res
    }, [block])

    return <BlockMemo defineProps={block.props}/>
})

export default Block
